package org.bot.server.utils;

import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;

/**
 * @Author: 沧月
 * @Date: 2023/12/11 13:30
 * @Description: 描述
 */
public class ServletUtils {


    public static void downEncryptionFile(HttpServletResponse response, Object data, String fileName) {
        try {
            byte[] encrypt = AESUtils.encrypt(data.toString());
            write(response, encrypt, fileName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void downEncryptionFile(HttpServletResponse response, String key, Object data, String fileName) {
        try {
            byte[] encrypt = AESUtils.encrypt(data.toString(), key);
            write(response, encrypt, fileName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    private static void write(HttpServletResponse response, byte[] encryptData, String fileName) {
        try {
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM.toString());
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            try (OutputStream out = response.getOutputStream()) {
                out.write(encryptData);
                out.flush();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
